<?php
/**
 * This file is part of Task Agile.
 * Task Agile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License.
 * Task Agile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Task Agile.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category   TaskAgile
 * @package    Controller
 * @copyright  Copyright (c) 20010-2010 Estrada Virtual (http://estradavirtual.com.br)
 * @license    http://www.gnu.org/licenses/gpl.txt GPLv3
 * @version    $Id$
*/
class enterprise_EnterpriseController extends Tev_Controller_Crud
{
    public function formAction()
    {
        // Users
        $user = new User();
        $rowSetUsers = $user->fetchAll(null, 'name');
        unset($user);
        $users = array();
        foreach ($rowSetUsers as $rowUser) {
            $users[$rowUser->id] = $rowUser->name;
        }
        $this->view->users = $users;
        unset($users);

        $model = new Enterprise();
        if ($id = $this->_getParam('id', false)) {
            $row = $model->find($id)->current();

            // enterprise_user
            $usersSelected = array();
            $rowSetEnterpriseUser = $row->findEnterpriseUser();
            foreach ($rowSetEnterpriseUser as $rowEnterpriseUser) {
                $usersSelected[] = $rowEnterpriseUser->fk_user;
            }
            $this->view->usersSelected = $usersSelected;
        } else {
            $row = $model->createRow();
        }
        $this->view->row = $row;
    }

    public function saveAction()
    {
        $model = new Enterprise();
        if ($id = $this->_getParam('id', false)) {
            $row = $model->find($id)->current();
        } else {
            $row = $model->createRow();
            $row->dt_register = date('Y-m-d H:i:s');
        }
        $row->name = $this->_getParam('name');
        $idEnterprise = $row->save();

        // enterprise_user
        $enterpriseUser = new EnterpriseUser();
        // @todo ver como tratar esse caso
        $enterpriseUser->delete('fk_enterprise = ' . $idEnterprise);
        $users = $this->_getParam('users', array());
        foreach ($users as $idUser) {
            $row = $enterpriseUser->createRow();
            $row->fk_user = $idUser;
            $row->fk_enterprise = $idEnterprise;
            $row->save();
        }

        $this->_redirect('enterprise/enterprise/list');
    }
}